/*
 * @Description: 
 * @Author: 姜暖阳
 * @Date: 2021-07-08 15:10:26
 * @LastEditTime: 2022-12-05 12:47:33
 * @LastEditors: 赵大壮
 * @Reference: 
 */
// 1. 请求 OK
// 2. get/post get转换拼接方式 post根据body等 OK
// 3. promise OK
// 4. 错误代码 OK
// 5. 服务端配置错误代码 OK
// 6. 不同服务器地址切换 OK
// 7. 图片/文件上传/下载 OK
// 8. mock

import request from './nyRequest'
import api from './nyApiJson'
import axios from 'axios'
import ny_config from './nyConfig'
import nyMessageToast from '../utils/NYMessageToast'
import store from '@/store'
import router from '@/router'

class nyNet {
    install() {
        // 初始化调用
    }
    public net(apiName: string, parameter: { [key: string]: any } = {}, success: (response: any) => void) {
        var apiJson: ny_config = api[apiName];

        if (!apiJson) {
            console.error('未找到对应的网络接口 <' + apiName + ">");
            return;
        }

        var headers = null;

        store.state.user.updateCache();
        // if (store.state.user.checkOverdue()) {
        //     nyMessageToast.warning('登录超时，请重新登录');
        //     store.commit("SET_USER", {});
        //     store.state.user.logout();
        //     router.push({ path: '/index' });
        //     return;
        // }

        if (apiJson.useToken == true) {
            if (store.state.user.isLogin()) {
                headers = {
                    "Authorization": store.state.user.token
                };
            }
        }

        var net_request = request({
            baseURL: apiJson.baseUrl,
            url: apiJson.url,
            method: 'post',
            data: parameter,
            timeout: apiJson.timeout, // 请求超时时间
            headers: headers
        }).then(function (response: any) {
            if (response.code == -1008) {
                console.log('登录信息已被清除 = ', response);
                nyMessageToast.error('您的账号已在其他设备登录');
                store.commit("SET_USER", {});
                store.state.user.logout();
                router.push({ path: '/index' });
            }
            else if (response.code != 200) {
                if (apiJson.showFailMessage) {
                    if (response.msg) {
                        nyMessageToast.error(response.msg);
                    }
                    else {
                        console.log('response.message错误', response);
                    }
                }
                else {
                    console.log('请求失败但不提示信息，如需修改在nyApiJson中修改配置', response);
                }
            }
            else {
                if (apiJson.showSuccessMessage) {
                    if (response.msg) {
                        nyMessageToast.success(response.msg);
                    }
                    else {
                        console.log('response.message错误', response);
                    }
                }

                success(response.data);
            }
        })
            .catch(function (error) {
                console.log(error);
            });

        return net_request
    }

    upload(apiName: string, upload_type: string, file: File, progress: Function, success: Function, error: Function) {
        var apiJson = api[apiName];

        let formData = new FormData();
        formData.append("upload_type", upload_type)
        formData.append("uploadFile", file);

        axios.defaults.withCredentials = false;

        const config = {
            headers: { "Content-Type": "multipart/form-data" },
            onUploadProgress: function (e: any) {
                let percentage = Math.round((e.loaded * 100) / e.total) || 0
                console.log(e, percentage)
                progress(percentage);
            }
        };
        if (apiJson.useToken) {
            config.headers["Authorization"] = store.state.user.token;
        }

        axios
            .post(process.env.VUE_APP_BaseURL + apiJson.url, formData, config)
            .then(function (response: any) {
                console.log("response", response)
                if (response.data.code == 200) {
                    success(response.data.data);
                } else if (response.data.code == 21) {
                    console.log('登录信息已被清除 = ', response);
                    nyMessageToast.error('您的账号已在其他设备登录');
                    store.commit("SET_USER", {});
                    store.state.user.logout();
                    router.push({ path: '/index' });
                } else {
                    error();

                }
            })
            .catch(function (er) {
                error();
                console.log("error", er);
            });
    }


    public down(apiName: string, parameter: { [key: string]: any } = {} ,fileName) {
        var apiJson: ny_config = api[apiName];
        if (!apiJson) {
            console.error('未找到对应的网络接口 <' + apiName + ">");
            return;
        }
        var headers = null;
        store.state.user.updateCache();
        if (apiJson.useToken == true) {
            if (store.state.user.isLogin()) {
                headers = {
                    "Authorization": store.state.user.token
                };
            }
        }
        var net_request = request({
            baseURL: apiJson.baseUrl,
            url: apiJson.url,
            method: 'post',
            data: parameter,
            timeout: apiJson.timeout, // 请求超时时间
            headers: headers,
            responseType: 'blob',
        }).then(function (response: any) {
            const blob = new Blob([response])
            // FileSaver.saveAs(blob, fileName)
            if ('download' in document.createElement('a')) { // 非IE下载
                const elink = document.createElement('a')
                elink.download = fileName + '.xlsx'
                elink.style.display = 'none'
                elink.href = URL.createObjectURL(blob)
                document.body.appendChild(elink)
                elink.click()
                URL.revokeObjectURL(elink.href) // 释放URL 对象
                document.body.removeChild(elink)
            }
        }).catch(function (error) {
            console.log(error);
        });

        return net_request
    }

    public downFile(apiName: string, parameter: { [key: string]: any } = {}, fileName: string) {
        var apiJson: ny_config = api[apiName];
        if (!apiJson) {
            console.error('未找到对应的网络接口 <' + apiName + ">");
            return;
        }
        var headers = null;
        store.state.user.updateCache();
        if (apiJson.useToken == true) {
            if (store.state.user.isLogin()) {
                headers = {
                    "Authorization": store.state.user.token
                };
            }
        }
        var net_request = request({
            baseURL: apiJson.baseUrl,
            url: apiJson.url,
            method: 'post',
            data: parameter,
            timeout: apiJson.timeout, // 请求超时时间
            headers: headers,
            responseType: 'blob',
        }).then(function (response: any) {
            const blob = new Blob([response])
            // FileSaver.saveAs(blob, fileName)
            if ('download' in document.createElement('a')) { // 非IE下载
                const elink = document.createElement('a')
                elink.download = fileName
                elink.style.display = 'none'
                elink.href = URL.createObjectURL(blob)
                document.body.appendChild(elink)
                elink.click()
                URL.revokeObjectURL(elink.href) // 释放URL 对象
                document.body.removeChild(elink)
            }
        }).catch(function (error) {
            console.log(error);
        });

        return net_request
    }



    download(apiName: string, params: string) {
        var apiJson: ny_config = api[apiName];
        if (!apiJson) {
            console.error('未找到对应的网络接口 <' + apiName + ">");
            return;
        }
        var link = document.createElement('a');//a标签下载
        link.href = apiJson.baseUrl + apiJson.url + params;
        // link.download = name;
        link.click();
    }

    image(id: string) {
        if (!id) {
            return "";
        }
        var apiName = "显示图片";
        var apiJson: ny_config = api[apiName];
        if (!apiJson) {
            console.error('未找到对应的网络接口 <' + apiName + ">");
            return "";
        }
        return apiJson.baseUrl + apiJson.url + "?image=" + id;
    }

    video(id: string) {
        if (!id) {
            return "";
        }
        var apiName = "播放视频";
        var apiJson: ny_config = api[apiName];
        if (!apiJson) {
            console.error('未找到对应的网络接口 <' + apiName + ">");
            return "";
        }
        return apiJson.baseUrl + apiJson.url + "?id=" + id;
    }

    // image(apiName: string, image: string, success: (url) => void) {
    //     var apiJson: ny_config = api[apiName];
    //     if (!apiJson) {
    //         console.error('未找到对应的网络接口 <' + apiName + ">");
    //         return;
    //     }
    //     request({
    //         baseURL: apiJson.baseUrl,
    //         url: apiJson.url,
    //         method: 'get',
    //         params: { image: image },
    //         timeout: apiJson.timeout, // 请求超时时间
    //         responseType: 'blob',
    //         headers: {
    //             Accept: 'application/octet-stream'
    //         }
    //     }).then((response: any) => {
    //         console.log(response)
    //         var blob = new Blob([response], { type: "image/jpeg" });
    //         var imageUrl = URL.createObjectURL(blob);;
    //         console.log("imageUrl", imageUrl)
    //         success(imageUrl);
    //     }).catch(function (error) {
    //         console.log("error", error);
    //     });
    // }
}

const nyNetwork = new nyNet();

export default nyNetwork